package com.conn3cted.phrasebook.web;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.conn3cted.phrasebook.domain.Person;

@Controller
public class ImageController {

	 @RequestMapping(value="resource/images/person", method = RequestMethod.GET)
	    public ModelAndView getProductAdditionalImage(@RequestParam("pId") long personId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		 	Person person = Person.findPerson(personId);
		 	byte[] content = person.getFile();
		 	if (person != null && content != null && content.length > 0) {
		 		
				response.setContentType(person.getFileContentType());
				response.setContentLength(content.length);
				
				FileCopyUtils.copy(new ByteArrayInputStream(content), response.getOutputStream());
				return null;
		 	}
		 	
		 	InputStream is = this.getClass().getResourceAsStream("noProfile.jpg");
		 	FileCopyUtils.copy(is, response.getOutputStream());
		 	
		 	return null;
	    }

}
